package com.example.chamberlainserver.Service.impl;

import com.example.chamberlainserver.Entry.TimeReport;
import com.example.chamberlainserver.Service.TimeReportService;
import com.example.chamberlainserver.Vo.Request.TimeReport.TimeReportQuery;
import com.example.chamberlainserver.dto.PageResult;
import com.example.chamberlainserver.mapper.TimeReportMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 时间填报服务实现类
 */
@Slf4j
@Service
public class TimeReportServiceImpl implements TimeReportService {
    
    @Autowired
    private TimeReportMapper timeReportMapper;
    
    @Override
    @Transactional
    public boolean addTimeReport(TimeReport timeReport) {
        log.info("添加时间填报记录: {}", timeReport);
        try {
            // 检查同一用户同一天是否已有填报记录
            TimeReport existingReport = timeReportMapper.getTimeReportByUserIdAndDate(
                timeReport.getUserId(), timeReport.getReportDate());
            if (existingReport != null) {
                log.warn("用户{}在{}已有填报记录", timeReport.getUserId(), timeReport.getReportDate());
                return false;
            }
            
            // 设置默认状态为待审核
            if (timeReport.getStatus() == null) {
                timeReport.setStatus(TimeReport.STATUS_PENDING);
            }
            
            int result = timeReportMapper.insertTimeReport(timeReport);
            log.info("添加时间填报记录结果: {}", result > 0 ? "成功" : "失败");
            return result > 0;
        } catch (Exception e) {
            log.error("添加时间填报记录失败", e);
            return false;
        }
    }
    
    @Override
    public TimeReport getTimeReportById(Integer id) {
        log.info("根据ID查询时间填报记录: {}", id);
        try {
            TimeReport timeReport = timeReportMapper.getTimeReportById(id);
            log.info("查询结果: {}", timeReport != null ? "找到记录" : "未找到记录");
            return timeReport;
        } catch (Exception e) {
            log.error("查询时间填报记录失败", e);
            return null;
        }
    }
    
    @Override
    public List<TimeReport> getTimeReportsByUserId(Integer userId) {
        log.info("根据用户ID查询时间填报记录列表: {}", userId);
        try {
            List<TimeReport> timeReports = timeReportMapper.getTimeReportsByUserId(userId);
            log.info("查询到{}条记录", timeReports.size());
            return timeReports;
        } catch (Exception e) {
            log.error("查询用户时间填报记录失败", e);
            return null;
        }
    }
    
    @Override
    public TimeReport getTimeReportByUserIdAndDate(Integer userId, LocalDate reportDate) {
        log.info("根据用户ID和日期查询时间填报记录: userId={}, date={}", userId, reportDate);
        try {
            TimeReport timeReport = timeReportMapper.getTimeReportByUserIdAndDate(userId, reportDate.toString());
            log.info("查询结果: {}", timeReport != null ? "找到记录" : "未找到记录");
            return timeReport;
        } catch (Exception e) {
            log.error("查询时间填报记录失败", e);
            return null;
        }
    }
    
    @Override
    public List<TimeReport> getAllTimeReports() {
        log.info("查询所有时间填报记录");
        try {
            List<TimeReport> timeReports = timeReportMapper.getAllTimeReports();
            log.info("查询到{}条记录", timeReports.size());
            return timeReports;
        } catch (Exception e) {
            log.error("查询所有时间填报记录失败", e);
            return null;
        }
    }
    
    @Override
    public List<TimeReport> getTimeReportsByStatus(Integer status) {
        log.info("根据状态查询时间填报记录: {}", status);
        try {
            List<TimeReport> timeReports = timeReportMapper.getTimeReportsByStatus(status.toString());
            log.info("查询到{}条记录", timeReports.size());
            return timeReports;
        } catch (Exception e) {
            log.error("根据状态查询时间填报记录失败", e);
            return null;
        }
    }
    
    @Override
    @Transactional
    public boolean updateTimeReport(TimeReport timeReport) {
        log.info("更新时间填报记录: {}", timeReport);
        try {
            int result = timeReportMapper.updateTimeReport(timeReport);
            log.info("更新时间填报记录结果: {}", result > 0 ? "成功" : "失败");
            return result > 0;
        } catch (Exception e) {
            log.error("更新时间填报记录失败", e);
            return false;
        }
    }
    
    @Override
    @Transactional
    public boolean deleteTimeReport(Integer id) {
        log.info("删除时间填报记录: {}", id);
        try {
            int result = timeReportMapper.deleteTimeReportById(id);
            log.info("删除时间填报记录结果: {}", result > 0 ? "成功" : "失败");
            return result > 0;
        } catch (Exception e) {
            log.error("删除时间填报记录失败", e);
            return false;
        }
    }
    
    @Override
    public PageResult<TimeReport> getPagedTimeReportList(TimeReportQuery timeReportQuery) {
        log.info("分页查询时间填报记录: {}", timeReportQuery);
        try {
            // 构建查询参数
            Map<String, Object> params = new HashMap<>();
            params.put("offset", (timeReportQuery.getPageNum() - 1) * timeReportQuery.getPageSize());
            params.put("limit", timeReportQuery.getPageSize());
            
            if (timeReportQuery.getUserId() != null) {
                params.put("userId", timeReportQuery.getUserId());
            }
            if (timeReportQuery.getStatus() != null) {
                params.put("status", timeReportQuery.getStatus());
            }
            if (timeReportQuery.getStartDate() != null) {
                params.put("startDate", timeReportQuery.getStartDate());
            }
            if (timeReportQuery.getEndDate() != null) {
                params.put("endDate", timeReportQuery.getEndDate());
            }
            if (timeReportQuery.getReviewerId() != null) {
                params.put("reviewerId", timeReportQuery.getReviewerId());
            }
            if (timeReportQuery.getUserName() != null && !timeReportQuery.getUserName().trim().isEmpty()) {
                params.put("userName", "%" + timeReportQuery.getUserName().trim() + "%");
            }
            if (timeReportQuery.getStuNo() != null && !timeReportQuery.getStuNo().trim().isEmpty()) {
                params.put("stuNo", "%" + timeReportQuery.getStuNo().trim() + "%");
            }
            
            // 查询数据和总数
            List<TimeReport> timeReports = timeReportMapper.getPagedTimeReportList(params);
            Long total = timeReportMapper.getPagedTimeReportCount(params);
            
            log.info("分页查询结果: 总数={}, 当前页数据量={}", total, timeReports.size());
            
            return new PageResult<>(timeReportQuery.getPageNum(), timeReportQuery.getPageSize(), total, timeReports);
        } catch (Exception e) {
            log.error("分页查询时间填报记录失败", e);
            return new PageResult<>(timeReportQuery.getPageNum(), timeReportQuery.getPageSize(), 0L, null);
        }
    }
    
    @Override
    @Transactional
    public boolean reviewTimeReport(Integer id, Integer status, Integer reviewerId, String reviewComment) {
        log.info("审核时间填报记录: id={}, status={}, reviewerId={}", id, status, reviewerId);
        try {
            TimeReport timeReport = new TimeReport();
            timeReport.setId(id);
            timeReport.setStatus(status.toString());
            timeReport.setReviewerId(reviewerId);
            timeReport.setReviewComment(reviewComment);
            timeReport.setReviewTime(LocalDateTime.now());
            
            int result = timeReportMapper.updateTimeReport(timeReport);
            log.info("审核时间填报记录结果: {}", result > 0 ? "成功" : "失败");
            return result > 0;
        } catch (Exception e) {
            log.error("审核时间填报记录失败", e);
            return false;
        }
    }
    
    @Override
    @Transactional
    public boolean batchReviewTimeReports(List<Integer> ids, Integer status, Integer reviewerId, String reviewComment) {
        log.info("批量审核时间填报记录: ids={}, status={}, reviewerId={}", ids, status, reviewerId);
        try {
            int result = timeReportMapper.batchUpdateStatus(ids, status.toString(), reviewerId, reviewComment);
            log.info("批量审核时间填报记录结果: 影响{}条记录", result);
            return result > 0;
        } catch (Exception e) {
            log.error("批量审核时间填报记录失败", e);
            return false;
        }
    }
    
    @Override
    public Double getTotalWorkHours(Integer userId, LocalDate startDate, LocalDate endDate) {
        log.info("统计用户工作时长: userId={}, startDate={}, endDate={}", userId, startDate, endDate);
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("userId", userId);
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            params.put("status", String.valueOf(TimeReport.STATUS_APPROVED)); // 只统计已通过的记录
            
            List<TimeReport> timeReports = timeReportMapper.getPagedTimeReportList(params);
            double totalHours = timeReports.stream()
                .mapToDouble(TimeReport::getWorkHours)
                .sum();
            
            log.info("统计结果: 总工作时长={}小时", totalHours);
            return totalHours;
        } catch (Exception e) {
            log.error("统计用户工作时长失败", e);
            return 0.0;
        }
    }
}